package com.markus.basic.设计模式.单例模式;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Author:markusZhang
 * Date:Create in 2020/8/24 15:56
 * todo: 测试demo
 */
public class TestDemo {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, IOException {
        //懒汉式
        System.out.println("懒汉式");
        SingleTon1 instance1 = SingleTon1.getInstance();
        SingleTon1 instance2 = SingleTon1.getInstance();
        //true
        System.out.println(instance1 == instance2);
        System.out.println("饿汉式");
        SingleTon2 instance3 = SingleTon2.getInstance();
        SingleTon2 instance4 = SingleTon2.getInstance();
        System.out.println(instance3 == instance4);
        System.out.println("双重检验锁");
        SingleTon3 instance5 = SingleTon3.getInstance();
        SingleTon3 instance6 = SingleTon3.getInstance();
        System.out.println(instance5 == instance6);
        //反射破坏单例模式
        System.out.println("利用反射破坏单例模式");
        Class clazz = Class.forName("com.markus.basic.设计模式.单例模式.SingleTon3");
        Constructor constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);
        SingleTon3 instance_re1 = (SingleTon3) constructor.newInstance();
        SingleTon3 instance_re2 = (SingleTon3) constructor.newInstance();
        System.out.println(instance_re1 == instance_re2);
        System.out.println("序列化破坏单例模式");
        SingleTon3 instance_ser = SingleTon3.getInstance();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
        oos.writeObject(SingleTon3.getInstance());
        File file = new File("tempFile");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        SingleTon3 instance_ds = (SingleTon3) ois.readObject();
        System.out.println(instance_ser == instance_ds);
        System.out.println("静态内部类");
        SingleTon4 instance7 = SingleTon4.getInstance();
        SingleTon4 instance8 = SingleTon4.getInstance();
        System.out.println(instance7 == instance8);
        System.out.println("枚举");
        SingleTon5 instance9 = SingleTon5.SINGLE_TON_5;
        SingleTon5 instance10 = SingleTon5.SINGLE_TON_5;
        System.out.println(instance9 == instance10);
    }
}